package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public Result<String> save(DishDTO dto) {

        //1.创建dish对象
        Dish dish = new Dish();
        //2.dto属性拷贝到dish
        BeanUtils.copyProperties(dto,dish);
        //3.新增dish入库
        dishMapper.save(dish);
        //4.给dto的flavor对象设置dishId
        dto.getFlavors().forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        //5.批量新增入库即可
        dishFlavorMapper.batchSave(dto.getFlavors());


        //删除缓存
        clearCache("dish:categoryId:"+dish.getCategoryId());

        return Result.success();
    }


    public void clearCache(String keyPattern){
        Set keys = redisTemplate.keys(keyPattern);
        keys.forEach(key->{
            redisTemplate.delete(key);
        });
    }


    @Override
    public Result<PageResult> page(DishPageQueryDTO dto) {

        //分页查询
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<DishVO> page = dishMapper.page(dto);
        //结果封装
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return Result.success(pageResult);
    }

    @Override
    @Transactional
    public Result<String> deleteByIds(List<Long> ids) {
//        1.先判断删除的菜品中是否存在起售的
        Integer dishCount = dishMapper.selectDishCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (dishCount>0){
            throw new DeletionNotAllowedException("删除的菜品中包含启售中的");
        }
//        2.判断删除的菜品中是否有被套餐引用的
        Integer setmealCount = setmealDishMapper.selectSetmealCountByDishId(ids);
        if (setmealCount>0){
            throw new DeletionNotAllowedException("删除的菜品中包含被套餐引用的");
        }
//        3.删除dish表的数据
        dishMapper.deleteByIds(ids);
//        4.删除dishFlavor表的数据
        dishFlavorMapper.deleteByDishids(ids);

        clearCache("dish:categoryId:*");
        return Result.success();
    }

    @Override
    public Result<DishVO> selectDishWithFlavor(Long dishId) {

        //多表查询，一步到位
        DishVO dishVO = dishMapper.selectDishWithFlavors(dishId);

        return Result.success(dishVO);
    }

    @Override
    @Transactional
    public Result<String> update(DishDTO dto) {

//        1.修改dish表数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
//        2.删除中间表数据
        dishFlavorMapper.deleteByDishid(dto.getId());
//        3.添加新的中间表数据
        dto.getFlavors().forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.batchSave(dto.getFlavors());
        //清除缓存
        clearCache("dish:categoryId:*");
        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        //优先查询缓存
        List<DishVO> dishVOList= (List<DishVO>)redisTemplate.opsForValue().get("dish:categoryId:"+dish.getCategoryId());
        if(dishVOList!=null&&dishVOList.size()>0)
        {
            return dishVOList;
        }

        List<Dish> dishList = dishMapper.list(dish);

        dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //放入到缓存
        redisTemplate.opsForValue().set("dish:categoryId:"+dish.getCategoryId(),dishVOList);

        return dishVOList;
    }
}
